from rest_framework import serializers
from rest_framework.serializers import ModelSerializer

from apps.spit.models import User, Label


class UsersRegistSerializer(ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'


class UserDetailSerializer(serializers.ModelSerializer):
    """
    用户详细信息序列化器
    """
    labels = LabelSerializerSimple(required=False, many=True)
    username = serializers.CharField(read_only=True)
    questions = QuestionSerializerForList(read_only=True, many=True)
    answer_question = ReplySerializerForList(read_only=True, many=True)
    collected_articles = ArticleSerializerForList(read_only=True, many=True)
    enterpises = EnterpriseSerializerSimple(read_only=True, many=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile','realname','birthday','sex','avatar','website','email','city', 'address','labels','questions','answer_question','collected_articles','enterpises')


class UserLabelSerializer(serializers.ModelSerializer):
    """
    用户修改擅长技术 的序列化器
    """
    labels = serializers.PrimaryKeyRelatedField(required=True, many=True,queryset=Label.objects.all())

    class Meta:
        model = User
        fields = ('id','labels')


class UserPwdSerializer(serializers.ModelSerializer):
    """
    用户详修改密码序列化器
    """
    class Meta:
        model = User
        fields = ('password',)
        extra_kwargs = {
            'password': {'write_only': True}
        }

    def update(self, instance, validated_data):
        user = super().update(instance, validated_data)
        user.set_password(validated_data['password'])
        user.save()
        return user